/*
 * Copyright 2008 Jens Meiss
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.hmvc4gwt.framework.client.rpc;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.googlecode.hmvc4java.event.IEvent;
import com.googlecode.hmvc4java.event.IEventListener;

/**
 * 
 * 
 * @author jens.meiss
 */
public abstract class AAsyncCallback<T, E extends IEvent> implements AsyncCallback<T> {

	/**
	 * A eventListener receives the onSuccess(Object result)
	 */
	private IEventListener eventListener;
	
	private E eventOnSuccess;

	/**
	 * @return the eventListener
	 */
	protected IEventListener getEventListener() {
		return eventListener;
	}

	/**
	 * @return the eventOnSuccess
	 */
	private E getEventOnSuccess() {
		return eventOnSuccess;
	}

	public void onSuccess(T result) {
		
		E eventSuccess = getEventOnSuccess();
		eventSuccess.setPayload(result);
		
		getEventListener().handleEvent(eventSuccess);
	}
	
	public void onFailure(Throwable caught) {
		Window.alert(caught.getClass() + ": " + caught.getMessage());
	}
	
	/**
	 * @param eventListener the eventListener to set
	 */
	protected void setEventListener(IEventListener eventListener) {
		this.eventListener = eventListener;
	}
	
	/**
	 * @param eventOnSuccess the eventOnSuccess to set
	 */
	protected void setEventOnSuccess(E eventOnSuccess) {
		this.eventOnSuccess = eventOnSuccess;
	};
	
}
